import useAppStore from "@/store";
import Taro from "@tarojs/taro";
import dayjs from "dayjs";
import { useRef } from "react";

// 绘制水印（固定尺寸，放在图片的右下角）
function drawTextWithLineBreaks(
  strings,
  options = {
    fontSize: 15,
    radius: 16,
    fontFamily: "Arial",
    textColor: "white",
    padding: 20, // 四周边距 20px
    bgColor: "rgba(0, 0, 0, 0.3)", // 白色背景，透明度 50%
  }
) {
  const width = 320;
  const height = 220;

  // 获取离屏画布
  const canvas = Taro.createOffscreenCanvas({
    type: "2d",
    width,
    height,
  });

  const { fontSize, fontFamily, textColor, padding, bgColor, radius } = options;

  const ctx = canvas.getContext("2d") as any;

  // 1. 创建圆角矩形路径
  ctx.beginPath();
  ctx.moveTo(radius, 0);
  ctx.arcTo(width, 0, width, height, radius); // 右上角
  ctx.arcTo(width, height, 0, height, radius); // 右下角
  ctx.arcTo(0, height, 0, 0, radius); // 左下角
  ctx.arcTo(0, 0, width, 0, radius); // 左上角
  ctx.closePath();

  // 2. 设置裁剪区域
  ctx.clip();

  // 1. 绘制半透明白色背景（覆盖整个画布）
  ctx.fillStyle = bgColor;
  ctx.fillRect(0, 0, width, height);

  // 2. 设置文字样式
  ctx.font = `${fontSize}px ${fontFamily}`;
  ctx.fillStyle = textColor;
  ctx.textAlign = "left";
  ctx.textBaseline = "top";

  // 行高（字体大小 + 行间距）
  const lineHeight = fontSize * 1.5;
  let currentY = padding; // 起始 Y 坐标（考虑 padding）

  // 3. 遍历每个字符串并绘制
  for (const text of strings) {
    // 如果超出画布高度（考虑底部 padding），停止绘制
    if (currentY + lineHeight > canvas.height - padding) break;

    // 拆分长文本为多行（自动换行，宽度需扣除左右 padding）
    const lines = wrapText(ctx, text, canvas.width - 2 * padding);

    // 绘制每一行
    for (const line of lines) {
      // 检查是否超出画布底部边界
      if (currentY + lineHeight > canvas.height - padding) break;

      // 绘制文本（x 坐标考虑左侧 padding）
      ctx.fillText(line, padding, currentY);
      currentY += lineHeight;
    }
  }

  return canvas;
}
// 自动换行逻辑（保持不变）
function wrapText(ctx, text, maxWidth) {
  const words = text.split("");
  const lines: string[] = [];
  let currentLine = words[0] || "";

  for (let i = 1; i < words.length; i++) {
    const word = words[i];
    const testLine = currentLine + " " + word;
    const metrics = ctx.measureText(testLine);

    if (metrics.width <= maxWidth) {
      currentLine = testLine;
    } else {
      lines.push(currentLine);
      currentLine = word;
    }
  }

  if (currentLine) lines.push(currentLine);

  return lines;
}

const setWaterMask = async (
  canvas: any,
  ctx: any,
  imageInfo: Taro.ImageData,
  maskCanvas: any
) => {
  // 1. 绘制原始图片
  ctx.drawImage(imageInfo, 0, 0, imageInfo.width, imageInfo.height);

  // 2. 绘制水印
  ctx.save();
  ctx.drawImage(maskCanvas, 10, 10);
  // 与save配套
  ctx.restore();

  // 转为临时图片路径
  const res = await Taro.canvasToTempFilePath({
    canvas,
    destWidth: imageInfo.width,
    destHeight: imageInfo.height,
  });

  return res.tempFilePath;
};

export default (callback?: (path: string) => void) => {
  const canvasRef = useRef<any>();
  const maskRef = useRef<any>();

  const userinfo = useAppStore((state) => state.userInfo);

  const createMaskImage = async () => {
    if (!maskRef.current) {
      const maskTexts = await getMaskText();
      maskRef.current = drawTextWithLineBreaks(maskTexts);
    }
  };

  const getLocation = async () => {
    try {
      const { longitude, latitude } = await Taro.getLocation({
        type: "gcj02",
        altitude: false,
        isHighAccuracy: false,
      });

      /**
       * 可以通过对比 longitude/latitude 与res的经纬度是否一致，判断用户是否有手动更改位置
       */
      const res = await Taro.chooseLocation({ longitude, latitude });
      return res;
    } catch (err) {
      console.error("未授权定位", err);
      Taro.showToast({ icon: "none", title: "未授权定位" });
    }
  };

  const getMaskText = async () => {
    const res = await getLocation();
    const { user_name, user_id, user_code } = userinfo;
    const date = dayjs().format("YYYY-MM-DD HH:mm:ss");

    const strings = [
      `创建人ID:${user_id}(${user_code})`,
      `创建人:${user_name}`,
      `经度:${res?.longitude || "-"}`,
      `纬度:${res?.latitude || "-"}`,
      `地址:${res?.address || "-"}`,
      `时间:${date}`,
    ];

    return strings;
  };

  const createImageInfo = (canvas, path): Promise<Taro.ImageData> => {
    return new Promise((resolve, reject) => {
      const image = canvas.createImage();

      image.onload = () => {
        resolve(image);
      };

      image.onerror = () => {
        reject();
      };

      image.src = path;
    });
  };

  const drawMaskImage = async (tempFilePath: string) => {
    await createMaskImage();

    const canvas = canvasRef.current;

    if (canvas) {
      const imageInfo = await createImageInfo(canvas, tempFilePath);
      canvas.width = imageInfo.width;
      canvas.height = imageInfo.height;

      const ctx = canvas.getContext("2d");

      const reuslt = await setWaterMask(
        canvas,
        ctx,
        imageInfo,
        maskRef.current
      );

      // 清空canvas
      ctx.clearRect(0, 0, 0, 0);
      canvas.width = 0;

      return reuslt;
    }
  };

  const batchDrawImage = async (tempFilePaths: any[]) => {
    let list: any = [];

    while (tempFilePaths.length > 0) {
      const tempFilePath = tempFilePaths.shift();
      const src = await drawMaskImage(tempFilePath);

      if (src) {
        list.push(src);
        callback?.(src);
      }
    }

    return list;
  };

  return {
    canvasRef,
    drawMaskImage,
    batchDrawImage,
  };
};
